<script>
	import TIM from 'tim-wx-sdk'
	import COS from 'cos-wx-sdk-v5';
	import {
		genTestUserSig,
		SDKAPPID
	} from 'plugins/generateTestUserSig.js'
	import { unread } from 'http/apis/Message.js'

	export default {
		onLaunch: function() {

			uni.setStorageSync(`TIM_${SDKAPPID}_isTUIKit`, true);
			uni.$TUIKit = TIM.create({
				SDKAppID: SDKAPPID
			});
			uni.$TUIKit.registerPlugin({
				'cos-wx-sdk': COS
			});

			// 如果您已创建了 tim，请将 tim 实例挂载在 wx 上，且不可以修改 wx.$TIM（修改变量可能导致 TUICalling 组件无法正常使用）, 完成 TUICalling 初始化，
			// 如果您没有创建，可以不传
			// #ifdef MP-WEIXIN
			// wx.$TIM = uni.$TUIKit;
			// #endif
			uni.$TUIKitTIM = TIM;
			uni.$TUIKitEvent = TIM.EVENT;
			uni.$TUIKitVersion = TIM.VERSION;
			uni.$TUIKitTypes = TIM.TYPES; // 监听系统级事件
			uni.$TUIKit.on(uni.$TUIKitEvent.SDK_READY, this.onSDKReady);
			uni.$TUIKit.on(uni.$TUIKitEvent.SDK_NOT_READY, this.onSdkNotReady);
			uni.$TUIKit.on(uni.$TUIKitEvent.KICKED_OUT, this.onKickedOut);
			uni.$TUIKit.on(uni.$TUIKitEvent.ERROR, this.onTIMError);
			uni.$TUIKit.on(uni.$TUIKitEvent.NET_STATE_CHANGE, this.onNetStateChange);
			uni.$TUIKit.on(uni.$TUIKitEvent.SDK_RELOAD, this.onSDKReload);
			uni.$TUIKit.on(uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated);
			uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.onMessageReceived);


			//重新设置用户信息
			uni.$LTResetLoginData = this.resetLoginData;
			uni.$LTLogin = this.liaotianLogin;
			uni.$LTUpdateMyInfo = this.ltUpdateMyInfo;
		},
		onShow: function() {
			let menuButtonObject = wx.getMenuButtonBoundingClientRect();
			this.menuButtonObject = menuButtonObject
			wx.getSystemInfo({
				success: res => {
					//导航高度
					let statusBarHeight = res.statusBarHeight,
						navTop = menuButtonObject.top,
						navObjWid = res.windowWidth - menuButtonObject.right + menuButtonObject
						.width, // 胶囊按钮与右侧的距离 = windowWidth - right+胶囊宽度
						navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top -
							statusBarHeight) * 2;
					this.globalData.navHeight = navHeight; //导航栏总体高度
					this.globalData.navTop = navTop; //胶囊距离顶部距离
					this.globalData.navObj = menuButtonObject.height; //胶囊高度
					this.globalData.navObjWid = navObjWid; //胶囊宽度(包括右边距离)
					console.log(this.globalData)
					// console.log(navHeight,navTop,menuButtonObject.height,navObjWid)
				},
				fail(err) {
					console.log(err);
				}
			})
		},
		onHide: function() {},
		globalData: {
			allUnread: 0,
			navHeight: 0,
			navTop: 0,
			navObj: 0,
			navObjWid: 0,
			// userInfo: userID userSig token phone
			userInfo: {
				userID: '',
				userSig: ""
			},
			// 个人信息
			userProfile: {},
			isTUIKit: true,
			headerHeight: 0,
			statusBarHeight: 0,
			SDKAppID: SDKAPPID,
			isSDKReady: false,

			conversationList: []
		},
		methods: {
			// 会话列表
			async onConversationListUpdated(event) {

				// console.log(event, event.data); // 包含 Conversation 实例的数组

				getApp().globalData.conversationList = event.data
				// const { data } = await this.$http.Message.imCover()
				// console.log(data)
				// getApp().globalData.conversationList = event.data
			},
			onTIMError(event) {
				console.info("聊天-SDK遇到错误时触发", event)
				uni.showModal({
					title: "系统提示",
					content: '初始化聊天错误：' + event.data.code + "," + event.data.message,
				})
			},
			onSDKReady({
				name
			}) {
				console.info("聊天-SDK进入ready状态时触发", name)
				const isSDKReady = name === uni.$TUIKitEvent.SDK_READY ? true : false
				getApp().globalData.isSDKReady = true
				this.ltUpdateMyInfo()


			},
			onMessageReceived(event) {
				console.log(event,this)
				unread().then(res => {
					console.log(res)
					getApp().globalData.allUnread = res.data.all
				})
				getApp().globalData.messageReceiedList.push(event.data)
			
				
				
			},
	
			onSdkNotReady() {
				console.info("聊天-SDK进入not ready状态时触发")
				getApp().globalData.isSDKReady = false
			},
			onNetStateChange(event) {
				console.info("聊天-网络状态改变通知", event)
				// v2.5.0 起支持
				// event.data.state 当前网络状态，枚举值及说明如下：
				// TIM.TYPES.NET_STATE_CONNECTED - 已接入网络
				// TIM.TYPES.NET_STATE_CONNECTING - 连接中。很可能遇到网络抖动，SDK 在重试。接入侧可根据此状态提示“当前网络不稳定”或“连接中”
				// TIM.TYPES.NET_STATE_DISCONNECTED - 未接入网络。接入侧可根据此状态提示“当前网络不可用”。SDK 仍会继续重试，若用户网络恢复，SDK 会自动同步消息

			},
			onSDKReload() {
				console.info("聊天-SDK重启")
			},
			onKickedOut() {
				console.info("聊天-用户被踢下线时触发")
				uni.showModal({
					title: "系统提示",
					content: '您的聊天账号在另一台设备登陆,若不是本人，请联系管理员',
				})


			},
			liaotianLogin(userID) {
				// if (getApp().globalData.isSDKReady === true) {
				// 	if (this.isNotNull(event)) {
				// 		event(true)
				// 	}
				// 	return
				// }
				// this.resetLoginData()
				console.info("签名", getApp().globalData.userInfo)
				uni.$TUIKit.login({
						userID,
						userSig: genTestUserSig(userID).userSig
					})
					.then((imResponse) => {
						console.log("登陆结果", imResponse.data); // 登录成功
						if (imResponse.data.repeatLogin === true) {
							// 标识帐号已登录，本次登录操作为重复登录。v2.5.1 起支持
							console.log("登陆成功", imResponse.data.errorInfo);
						} else {
							// let interval = setInterval(() => {
							// console.info("sdk是否准备", getApp().globalData.isSDKReady)
							// 	if (getApp().globalData.isSDKReady === true) {
							// 		if (this.isNotNull(event)) {
							// 			clearInterval(interval)
							// 			event(true)
							// 		}
							// 	}
							// }, 100)
						}
					})
					.catch((imError) => {
						console.warn('登陆失败:', imError); // 登录失败的相关信息
						uni.showModal({
							title: "系统提示",
							content: "聊天登陆失败，请稍后重试" + JSON.stringify(imError),
						})
						event(false)
					});
			},
			// 聊天 - 初始化数据
			resetLoginData() {
				//从数据库获取到用户信息
				let userInfo = {
					fbNickName: "闫伟",
					fbAvatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/LWicoUend7QOfiabWDRjfpPDB51LzhbzVzjibicqDD2ztqy7BlpicRn8HToMoDVg9g1XfNiayHStXfC2f6yGNHgLueEw/132",
					liaotianId: "lt402882f280bb92810180bbb3f40a000f",
				}
				getApp().globalData.expiresIn = '';
				getApp().globalData.sessionID = '';
				getApp().globalData.userInfo = {
					userID: userInfo.liaotianId,
					userSig: genTestUserSig(userInfo.liaotianId).userSig,
				};
				getApp().globalData.userProfile = {
					userID: userInfo.liaotianId,
					nick: userInfo.fbNickName,
					avatar: userInfo.fbAvatarUrl
				};
			},
			ltUpdateMyInfo() {
				if (getApp().globalData.isSDKReady === true) {
					// let userInfo = this.$user.getUserInfo()
					// 修改个人标配资料
					let promise = uni.$TIM.updateMyProfile({
						nick: userInfo.fbNickName,
						avatar: userInfo.fbAvatarUrl,
						// allowType: uni.$TIM.TYPES.ALLOW_TYPE_ALLOW_ANY
					});
					promise.then(function(imResponse) {
						console.log("更新资料成功", imResponse.data); // 更新资料成功
					}).catch(function(imError) {
						console.warn('updateMyProfile error:', imError); // 更新资料失败的相关信息
					});
				}
			},
			/**
			 * 是否不为空
			 * @param {Object} params
			 */
			isNotNull(params) {
				if (typeof(params) === 'undefined') {
					return false
				} else if (params == null) {
					return false
				}

				return true
			}
		},


	}
</script>

<style lang="less">
	@import "colorui/main.css";
	// @import "colorui/icon.css";

	page {
		background: #fff;
	}

	* {
		background: #fff;

	}

	button {
		padding: 0;
	}
</style>
